package org.come.socket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import org.come.action.MapAction;

public class GameClientHandler extends SimpleChannelInboundHandler<String> {
	private GameClient client;
	public GameClientHandler(GameClient client) {
		this.client = client;
	}
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.close();
		super.exceptionCaught(ctx, cause);
	}
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {//biubiu
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			if (event.state() == IdleState.WRITER_IDLE)
			/** zrikka 2020 0414 */
//                if ("login".equals(client.getServerType())) {
//                    SendMessageUntil.loginToServer("bibi");
//                } else {
            {
                SendMessageUntil.toServer("bibi");
            }
//                }
			/*****/
		}
		super.userEventTriggered(ctx, evt);
	}
	/**收到服务器的消息*/
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) {
		try {
			if (msg==null) {
				return;
			}
			MapAction.mesControl.controlMessFromServer(msg, null);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}//
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// 将通信赋值
		/** zrikka 2020 0414 */
		StringBuffer key = new StringBuffer();
		key.append(client.getIp());
		key.append("|");
		key.append(client.getPort());
		// 将通信赋值 键: ip|port
		MapAction.nettyAction.put(key.toString(), ctx);
		MapAction.flagAction.put(key.toString(), true);
//		SendMessageUntil.SendMesToServer = ctx;
		/***/
		super.channelActive(ctx);
	}
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// 断线重来连告诉服务器将之前的数据保存
		/** zrikka 2020 0414 */
		StringBuffer key = new StringBuffer();
		key.append(client.getIp());
		key.append("|");
		key.append(client.getPort());
		// 断线重来连告诉服务器将之前的数据保存
		//system.out.println("断线");
		if (MapAction.flagAction.get(key.toString())) {
			MapAction.flagAction.put(key.toString(), false);
			client.doConnect();
		}
//		//system.out.println("断线");
//		if(SendMessageUntil.CanDoConnectOrNo){
//			SendMessageUntil.CanDoConnectOrNo=false;
//			client.doConnect();	
//		}
		/***/
		super.channelInactive(ctx);
	}
}